package com.xxja.order.config.interceptor;

import com.xxja.order.auth.user.pojo.User;
import com.xxja.order.utils.cookie.CookieUtils;
import com.xxja.order.utils.jwt.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final ThreadLocal<User> tl = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 查询token
//        System.out.println("111----------");
        String token = CookieUtils.getCookieValue(request, "user");
        if (StringUtils.isBlank(token)) {
            // 未登录 返回401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        // 有token，查询用户信息
        try {
            // 解析成功，证明已登录
            User user = JwtUtils.getUserFromToken(token);
            // 放入线程池
            tl.set(user);
            return true;
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        tl.remove();
    }

    public static User getLoginUser() {
        return tl.get();
    }
}
